﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using CMSModel;
using System.Text.RegularExpressions;
using System.Text;
using System.Xml;

/// <summary>
/// 抓取投资备忘数据
/// </summary>
public class TzbwBLL
{
    public void Import()
    {
        CMSEntities dal = new CMSEntities();
        DateTime? dd = dal.InvestmentMemo.Select(x => x.CTime).Max();
        DateTime time;
        if (dd == null)
            time = DateTime.Parse("2010-01-01");
        else
            time = dd.Value.AddDays(1);
        while (time <= DateTime.Now.Date)
        {
            string url = "http://stock.finance.qq.com/cgi-bin/sstock/w_tzbw?rq="+time.ToString("yyyy-MM-dd");
            WebClient client = new WebClient();
            string content= client.DownloadString(url);
            MatchCollection mc = Regex.Matches(content, Tzbw_Reg);
            for (int j = 0; j < mc.Count; j++)
            {
                Add(mc[j].Value,time);
            }
            time= time.AddDays(1);
        }
    }


    public void Add(string content,DateTime date)
    {
        content = content.Replace("&", "&amp;");
        content = "<root>" + content + "</root>";
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(content);
        XmlElement root = doc.DocumentElement;
        var trs = root.SelectNodes("tr");
        //类型
        var trLx = trs[0];
        string type = trLx.ChildNodes[0].InnerText;
        if (type.Contains("债券") || type.Contains("基金"))
        {
            return;
        }
        CMSEntities dal = new CMSEntities();
        for (int i = 1; i < trs.Count; i++)
        {
            InvestmentMemo m=new InvestmentMemo();
            string url= trs[i].ChildNodes[0].ChildNodes[0].Attributes["href"].Value;
            MatchCollection mc = Regex.Matches(url, "\\d{6}");
            if (mc.Count > 0)
            {
                m.Stock = mc[0].Value;
            }
            m.StockName = trs[i].ChildNodes[0].ChildNodes[0].InnerText;
            m.Content = trs[i].ChildNodes[1].InnerText;
            m.Type = type;
            m.CTime = date;
            if (!dal.InvestmentMemo.Any(x => x.CTime == m.CTime && x.Content == m.Content && x.Type == m.Type))
            {
                dal.InvestmentMemo.AddObject(m);
            }
        }
        dal.SaveChanges();
    }

    private string Tzbw_Reg
    {
        get
        {
            return "<tr bgcolor=\"#E8F3FB\"><td colspan=\"2\" align=\"left\">[\\s\\S]{2,30}</td></tr>\\s*(<tr\\svalign=\"top\" bgcolor=\"(()|(#FCFCFC))\"><td><a href=\"\\S*\\d{6}\"\\starget=\"_blank\">\\S{2,15}</a></td><td>[\\s\\S]{2,50}</td></tr>\\s*)*";
        }
    }
}